import { SearchToolComponent } from "./components/search-tool/search-tool.component";
import { DOCUMENT } from "@angular/common";
import { DrawThemeComponent } from "./components/draw-theme/draw-theme.component";
import { Router, NavigationEnd } from "@angular/router";
import { Component, OnInit, ViewChild, Renderer2, Inject } from "@angular/core";
import { Overlay, OverlayRef } from "@angular/cdk/overlay";
import { ComponentPortal } from "@angular/cdk/portal";
import { MatIcon } from "@angular/material/icon";
import { Store, select } from "@ngrx/store";
import { Selectors, AppState } from "./store";
import { MatDialog } from "@angular/material/dialog";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
  url: string = "";
  title = "Git 相册";
  theme: AppState[Selectors.theme]["theme"] = "primary";
  overlayRef: OverlayRef = null;

  @ViewChild("drawThemeIcon", { static: false }) drawThemeIcon: MatIcon;

  constructor(
    private router: Router,
    private overlay: Overlay,
    private rd2: Renderer2,
    private store$: Store<AppState>,
    public dialog: MatDialog,
    @Inject(DOCUMENT) private doc: Document
  ) {}

  ngOnInit(): void {
    this.checkRoute();
    this.store$.pipe(select(Selectors.theme)).subscribe(({ theme }) => {
      this.theme = theme;
    });
  }

  checkRoute() {
    this.router.events.subscribe(data => {
      if (data instanceof NavigationEnd) {
        this.url = data.url.substr(1);
      }
    });
  }

  openDrawTheme() {
    this.closeDrawThemePanel();
    const DrawThemePortal = new ComponentPortal(DrawThemeComponent);
    const positionStrategy = this.overlay
      .position()
      .flexibleConnectedTo(this.drawThemeIcon._elementRef)
      .withPositions([
        {
          originX: "center",
          originY: "bottom",
          overlayX: "center",
          overlayY: "bottom"
        }
      ]);
    this.overlayRef = this.overlay.create({ positionStrategy });
    this.overlayRef.attach(DrawThemePortal);
    const eventHandler = this.rd2.listen(this.doc.body, "click", e => {
      if (
        this.overlayRef &&
        this.overlayRef.hasAttached() &&
        this.overlayRef.overlayElement.contains(e.target)
      ) {
        this.overlayRef.dispose();
        eventHandler();
      }
    });
  }

  closeDrawThemePanel() {
    if (this.overlayRef && this.overlayRef.hasAttached()) {
      this.overlayRef.dispose();
    }
  }

  openSearch() {
    const dialogRef = this.dialog.open(SearchToolComponent, {
      width:
        this.doc.body.clientWidth > 900
          ? "30%"
          : this.doc.body.clientWidth > 500
          ? "60%"
          : "80%"
    });
  }
}
